<template>
  <div class="chat-window">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <div class="user-info">
        <el-avatar :size="40" :src="chatStore.currentChatUser?.avatar" class="user-avatar">
          {{ chatStore.currentChatUser?.username.charAt(0).toUpperCase() }}
        </el-avatar>
        <div class="user-details">
          <div class="username">{{ chatStore.currentChatUser?.username }}</div>
        <div class="user-status">
          <span class="status-dot" :class="{ online: chatStore.currentChatUser?.online }"></span>
          {{ chatStore.currentChatUser?.online ? '在线' : '离线' }}
          <span class="ws-status" :class="{ connected: chatStore.isConnected }">
            {{ chatStore.isConnected ? '●' : '○' }}
          </span>
        </div>
        </div>
      </div>
      <div class="chat-actions">
        <el-button size="small" text @click="loadMoreMessages">
          <el-icon><Refresh /></el-icon>
        </el-button>
        <el-button size="small" text @click="closeChat">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 消息列表 -->
    <div class="messages-container" ref="messagesContainer">
      <div v-if="chatStore.currentMessages.length === 0" class="no-messages">
        <el-empty description="暂无消息" :image-size="80" />
      </div>
      
      <div
        v-for="message in chatStore.currentMessages"
        :key="message.id"
        class="message-item"
        :class="{ 'own-message': message.sender_id === currentUserId }"
      >
        <div class="message-content">
          <div class="message-bubble">
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ formatMessageTime(message.created_at) }}</div>
          </div>
        </div>
      </div>
      
      <!-- 加载更多按钮 -->
      <div v-if="hasMoreMessages" class="load-more">
        <el-button size="small" @click="loadMoreMessages" :loading="chatStore.isLoading">
          加载更多消息
        </el-button>
      </div>
    </div>

    <!-- 消息输入框 -->
    <div class="message-input">
      <el-input
        v-model="messageText"
        placeholder="输入消息..."
        @keyup.enter="sendMessage"
        :disabled="!chatStore.currentChatUser"
        class="input-field"
      >
        <template #append>
          <el-button 
            type="primary" 
            @click="sendMessage"
            :disabled="!messageText.trim() || !chatStore.currentChatUser"
            :loading="sending"
          >
            发送
          </el-button>
        </template>
      </el-input>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch, onMounted, onUnmounted } from 'vue'
import { useChatStore } from '@/stores/chat'
import { useAuthStore } from '@/stores/auth'
import { Refresh, Close } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 定义props
interface Props {
  topicTitle?: string
}

const props = withDefaults(defineProps<Props>(), {
  topicTitle: ''
})

const chatStore = useChatStore()
const authStore = useAuthStore()

// 响应式数据
const messageText = ref('')
const sending = ref(false)
const messagesContainer = ref<HTMLElement>()
const currentPage = ref(1)
const hasMoreMessages = ref(true)

// 计算属性
const currentUserId = computed(() => authStore.userInfo?.id)

// 监听课题标题变化，预填充输入框
watch(() => props.topicTitle, (newTitle) => {
  if (newTitle && !messageText.value) {
    messageText.value = `您好！我想咨询关于"${newTitle}"这个课题的相关信息。`
  }
}, { immediate: true })

// 发送消息
const sendMessage = async () => {
  if (!messageText.value.trim() || !chatStore.currentChatUser || sending.value) {
    return
  }

  const content = messageText.value.trim()
  messageText.value = ''
  
  try {
    sending.value = true
    await chatStore.sendMessage(chatStore.currentChatUser.id, content)
    
    // 滚动到底部
    await nextTick()
    scrollToBottom()
  } catch (error) {
    ElMessage.error('发送消息失败')
    messageText.value = content // 恢复消息内容
  } finally {
    sending.value = false
  }
}

// 加载更多消息
const loadMoreMessages = async () => {
  if (!chatStore.currentChatUser || chatStore.isLoading) return
  
  try {
    currentPage.value++
    await chatStore.loadMessages(chatStore.currentChatUser.id, currentPage.value)
    
    // 检查是否还有更多消息
    if (chatStore.currentMessages.length < currentPage.value * 50) {
      hasMoreMessages.value = false
    }
  } catch (error) {
    ElMessage.error('加载消息失败')
    currentPage.value-- // 回退页码
  }
}

// 关闭聊天
const closeChat = () => {
  chatStore.clearCurrentChat()
  currentPage.value = 1
  hasMoreMessages.value = true
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 格式化消息时间
const formatMessageTime = (timeStr: string) => {
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 24小时内
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return date.toLocaleString('zh-CN', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
}

// 监听消息变化，自动滚动到底部
watch(
  () => chatStore.currentMessages.length,
  () => {
    nextTick(() => {
      scrollToBottom()
    })
  }
)

// 监听当前聊天用户变化
watch(
  () => chatStore.currentChatUser,
  (newUser) => {
    if (newUser) {
      currentPage.value = 1
      hasMoreMessages.value = true
    }
  }
)

// 键盘事件处理
const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

onMounted(() => {
  document.addEventListener('keydown', handleKeyDown)
  // 连接WebSocket
  chatStore.connectWebSocket()
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown)
  // 断开WebSocket连接
  chatStore.disconnectWebSocket()
})
</script>

<style scoped>
.chat-window {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #f8f9fa;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  margin-right: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 500;
  color: #1f2937;
  font-size: 16px;
}

.user-status {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #6b7280;
  margin-top: 2px;
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #d1d5db;
  margin-right: 4px;
}

.status-dot.online {
  background: #10b981;
}

.ws-status {
  margin-left: 8px;
  font-size: 12px;
  color: #d1d5db;
}

.ws-status.connected {
  color: #10b981;
}

.chat-actions {
  display: flex;
  gap: 8px;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.no-messages {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-item {
  display: flex;
  margin-bottom: 8px;
}

.message-item.own-message {
  justify-content: flex-end;
}

.message-content {
  max-width: 70%;
}

.message-bubble {
  background: #f1f3f4;
  border-radius: 18px;
  padding: 12px 16px;
  position: relative;
}

.own-message .message-bubble {
  background: #1890ff;
  color: white;
}

.message-text {
  font-size: 14px;
  line-height: 1.4;
  word-wrap: break-word;
}

.message-time {
  font-size: 11px;
  opacity: 0.7;
  margin-top: 4px;
  text-align: right;
}

.load-more {
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

.message-input {
  padding: 16px;
  border-top: 1px solid #e4e7ed;
  background: white;
}

.input-field {
  width: 100%;
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
